import { loginPhone } from '@/api/login'
import { getUserInfo } from '@/api/user.js'
import { setItem, getItem, removeItem } from '@/utils/storage'

const state = {
  username: '未登录',
  avatar: '',
  userId: getItem('NETEASE_USERID'),
  gender: '', // 1 = 男
  isVIP: '', // 0 = 非
  level: 0, // 等级
  listenSongs: 0 // 累计听歌
}

const mutations = {
  // 获取用户基本信息
  userInfo (state, payload) {
    state.username = payload.profile.nickname
    state.avatar = payload.profile.avatarUrl
    state.userId = payload.profile.userId
    state.gender = payload.profile.gender
    state.isVIP = payload.profile.vipType
    state.level = payload.level
    state.listenSongs = payload.listenSongs
    setItem('NETEASE_USERID', payload.profile.userId)
  },
  // 退出清空用户信息
  emptyData (state) {
    state.username = ''
    state.avatar = ''
    state.gender = ''
    state.isVIP = ''
    state.token = ''
    state.userId = ''
    removeItem('NETEASE_USERID')
  }
}

const actions = {
  async loginInfo (context, data) {
    try {
      const res = await loginPhone(data)
      context.commit('userInfo', res)
    } catch (err) {}
  },
  async loadUserInfo (context) {
    try {
      const res = await getUserInfo({ uid: context.state.userId })
      context.commit('userInfo', res)
    } catch (err) {}
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
